const util = require('util');
const debug = util.debuglog('oil-game:luckDraw:cron');

const schedule = require('node-schedule');
const async = require('async');
const dispatcher = require('../../../util/dispatcher');
const utils = require('../../../util/utils');

module.exports = function (app) { return new Handler(app); };
let Handler = function (app) { this.app = app; };
let handler = Handler.prototype;

//每分钟根据在线用户的数量投递宝箱
handler.deliveryPerMinute = async function () {
  //当前所有在线的用户
  let users = await getAllUsers.call(this);   
  if(users.length < 1) return;

  //随机发放宝箱
  randomGiveChest.call(this, users);
}

//汇总全部的Channel在线用户
async function getAllUsers(){
  try{
    let connectorServers = this.app.getServersByType('connector');
    let loginServers = this.app.getServersByType('login');
    let boxServers = this.app.getServersByType('box');
    if(!(loginServers && loginServers.length > 0)) return [];

    let users=[];
    for(let i = 0; i < loginServers.length; i++){
      let item = loginServers[i];
      let itemUsers = await getChannelAllUsers.call(this, item.id);

      for (let key in itemUsers) {    //获取所有的用户
        let { uid } = itemUsers[key];
        let server_id = item.id;
        let frontend_id = dispatcher.dispatch(uid, connectorServers).id;
        let box_sid = dispatcher.dispatch(uid, boxServers).id;
        users.push({ uid, server_id, frontend_id, box_sid });
      }
    }
    return users;
  }catch(err){ return []; }
}

//随机发放宝箱
function randomGiveChest(users){
  let { ordinary_treasure_num, superior_treasure_num } = utils.divideChestNumber(users.length);
  if (!(ordinary_treasure_num > 0 && users.length >= ordinary_treasure_num)) return; 

  for (let i = 0; i < ordinary_treasure_num; i++) {
    var key = Math.floor((Math.random() * users.length));
    let user = users[key]
    console.log('宝箱获奖用户 user = '+user.uid)
    //删除此客户
    users.splice(key, 1);
    //增加宝箱数量并通知客户端
    addChestNumAndPushMsg.call(this, user);
  }
}

//获取特定Channel中所有当前在线用户
function getChannelAllUsers(sid){
  return new Promise((resolve, reject) => {
    this.app.rpcInvoke(sid, {
      namespace: 'user',
      serverType: 'login',
      service: 'loginRemote',
      method: 'getAllUsers',
      args: [function() { }]
    }, function (err, result) {
      if(err) return reject(err);
      resolve(result);
    });
  });
}

//添加宝箱数量并通知客户端
function addChestNumAndPushMsg(user){
  this.app.rpcInvoke(user.box_sid, {
    namespace: 'user',
    serverType: 'box',
    service: 'boxRemote',
    method: 'deliverChest',
    args: [
      user.uid,   //用户id
      user.frontend_id,   //frontendId
      0 ]    //普通宝箱
  }, function(){} );
}
